import { defineStore } from 'pinia'
import type { ICartGoods } from '@/types/type'

export const useCollectionStore = defineStore('collection', {
    state() {
        return {
            //定义不同的变量，在不同的界面使用
            collectionList: [] as Array<ICartGoods>,
            stateAll: false,
        }
    },
    actions: {
        init(){
            this.stateAll = false
            this.collectionList.forEach(item => (item.state = false))
        },
        //复选框
        checkAll() {
            this.stateAll = !this.stateAll
            this.collectionList.forEach(item => (item.state = this.stateAll))
        },
        //单选
        singleCheck(id: number) {
            const goods: ICartGoods | undefined = this.collectionList.find(
                item => item.id === id
            )
            if (goods) {
                goods.state = !goods.state
            }
            this.stateAll = this.collectionList.every(item => item.state)
        },
        // 保存在store里面，收藏里面使用
        saveGoods(goods: ICartGoods) {
            // 相同商品数量加一
            // 判断购物车是否要添加商品如果有则添加数量，如果没有作为新商品添加
            const oldGoods: ICartGoods | undefined = this.collectionList.find(item => item.id === goods.id)
            if (oldGoods) {
                oldGoods.num++
            } else {
                this.stateAll = false//新加商品，全选状态设置为false
                this.collectionList.push(goods)
            }
        },
        //删除
        deleteGoods(id: number) {
            const index = this.collectionList.findIndex(item => item.id === id)
            this.collectionList.splice(index, 1)
        },
        //选择删除
        deleteChoose(state:boolean){
            const stateChoose=this.collectionList.filter(item=>item.state===state)
           stateChoose.forEach(item=>{
            this.collectionList.forEach((val,i)=>{
                if(item.id===val.id){
                    this.collectionList.splice(i,1)
                    this.stateAll=false
                }
            })
           })
           
            
        }
        // deleteAllGoods() {
        //     this.collectionList.splice(0, this.collectionList.length)
        // }
    },
    getters: {},
    persist: {
        enabled: true, //允许存储,默认true
        strategies: [
            {
                key: 'collection', //存储的数据名字
                storage: localStorage, //保存的类型，默认是session,
                paths: ['collectionList', 'stateAll'], //需要持久保存的state里面的数据
            },
        ],
    },
})
